﻿using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using EF.DB;

namespace DB.EF
{
    public class TransactionWrapper 
    {
        private MysqlContext _context;
        
        private IDbContextTransaction _transaction;


        public TransactionWrapper(MysqlContext context)
        {
            _context = context;
            _transaction = context.Database.BeginTransaction();
        }

        public void Commit()
        {
            try
            {
                // 执行提交操作前，可以添加自定义的逻辑
                _transaction.Commit();
            }
            catch
            {
                // 发生错误时，回滚事务
                Rollback();
                throw;
            }
            finally
            {
                // 释放资源
                _transaction.Dispose();
            }
        }

        public void Rollback()
        {
            try
            {
                _transaction.Rollback();
            }
            finally
            {
                _transaction.Dispose();
            }
        }

        // 使用using语句确保即使发生异常，事务也能正确回滚和处理
        public void UseTransaction(Action action)
        {
            try
            {
                action();
                this.Commit();
            }
            catch(Exception ex)
            {
                this.Rollback();
                throw ex;
            }
            //using (var transaction = _context.Database.BeginTransaction())
            //{
            //    try
            //    {
            //        action();
            //        transaction.Commit();
            //    }
            //    catch
            //    {
            //        transaction.Rollback();
            //        throw;
            //    }
            //}
        }
    }
}
